iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 18
0
Software Development

從零開始的Python練成記系列 第 18

[Day 18]物件導向一定要會的功能:繼承

  • 分享至 

  • xImage
  •  

對於不同類別的資料,可能會有不太一樣的輸出格式,但又不想要針對每個類別都寫不一樣的格式,這種時候就必須要用到今天的主軸,「繼承」,既可以將原本的資料存放方式向下延伸,又可以再將內部的屬性或輸出方式進行修改,真的是一舉兩得的設計呢~~~
對於今天的模擬題目就不多贅述,直接進到下方的程式碼吧:

#程式目標:設計一個百貨公司在周年慶時,用來辨識會員資料的功能
#其中,會員身分有分級,在進行購物時會因為自己的會員等級而享有不同的折扣
class Sogo(object):
    #預先設定基本值:一般會員,享有9折優惠,會存取會員的名字
    def __init__(self, total_cost, customer_name):
        self.discount = 0.9
        self.total_cost = total_cost
        self.customer_name = customer_name
    def printer(self):
        print("Hello, " + str(self.customer_name) + ", what do you want to buy today?")
    def check_out(self):
        return "The total is " + str(self.total_cost * self.discount)
    def print_check_out(self):
        print(Sogo.check_out(self))

class sliver_member(Sogo):
    #隨著會員等級的不同,系統也會有不一樣的問候語,這個設定是銀級會員的
    def __init__(self, total_cost, customer_name):
        self.discount = 0.85
        self.total_cost = total_cost
        self.customer_name = customer_name
    def printer(self):
        print("Welcome back, " + str(self.customer_name) + ", we have some discount for you today.")
    def check_out(self):
        #設定每個會員等級的結帳後問候語不同,在這裡就先引用一般會員的結帳問候語,然後再做改變
        return Sogo.check_out(self) + ", see you next time."
    def print_check_out(self):
        print(sliver_member.check_out(self))

class gold_member(sliver_member):
    #這個則是設定金級會員的
    def __init__(self, total_cost, customer_name):
        self.discount = 0.75
        self.total_cost = total_cost
        self.customer_name = customer_name
    def printer(self):
        print("Welcome back, " + str(self.customer_name) + ", how can we help you today?")
    def check_out(self):
        #同理,這裡也一樣做點變化
        return Sogo.check_out(self) + ", please come to VIP room to have some gifts."
    def print_check_out(self):
        print(gold_member.check_out(self))

CM1 = Sogo(28000, "Nick")
CM1.printer()
CM1.print_check_out()
print("")
SM1 = sliver_member(29000, "Linda")
SM1.printer()
SM1.print_check_out()
print("")
GM1 = gold_member(49000, "Wendy")
GM1.printer()
GM1.print_check_out()

就來看看結果吧:

"""
Hello, Nick, what do you want to buy today?
The total is 25200.0

Welcome back, Linda, we have some discount for you today
The total is 24650.0, see you next time

Welcome back, Wendy, how can we help you today?
The total is 36750.0, please come to VIP room to have some gifts.
"""

漫漫長路,鐵人賽也已經過了半個月


上一篇
[Day 17]除了物件導向,我把Input功能導入了
下一篇
[Day 19]資料結構:比Dictionary(目錄)架構更像二維陣列
系列文
從零開始的Python練成記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言